package com.hawk.eye.client.logback.provider;

import ch.qos.logback.classic.spi.CallerData;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.fasterxml.jackson.core.JsonGenerator;
import net.logstash.logback.composite.AbstractJsonProvider;

import java.io.IOException;

/**
 * @className: ErrorFileProvider
 * @description: 用于记录发生异常的代码类的Provider
 * @author: salad
 * @date: 2024/10/4
 **/
public class ErrorFileProvider extends AbstractJsonProvider<ILoggingEvent> {

    @Override
    public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException {
        generator.writeStringField("errorFileName", getFileName(event));
    }

    public static String getFileName(ILoggingEvent event) {
        StackTraceElement[] cda = event.getCallerData();
        String prefix = System.getProperty("hawk-eye.app-package-prefix");
        if (cda != null && cda.length > 1 && prefix != null) {
            StackTraceElement st = getStackTraceByPrefix(cda, prefix);
            if (st != null) {
                return st.getFileName() + "(" + st.getLineNumber() + ")";
            }
            return cda[0].getFileName() + "(" + cda[0].getLineNumber() + ")";
        } else {
            return CallerData.NA;
        }
    }

    /**
     * 获取指定包名为前缀的堆栈异常信息
     *
     * @param traces     异常
     * @param packagePrefix 指定的包前缀
     * @return 堆栈信息
     */
    public static StackTraceElement getStackTraceByPrefix( StackTraceElement[] traces, String packagePrefix) {
        for (StackTraceElement e : traces) {
            if (e.getClassName().startsWith(packagePrefix)) {
                return e;
            }
        }
        return null;
    }
}